package com.cwt.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author chenwt
 * @version V1.0
 * @description 【解决静态方法中mapper的调用】
 * @since 2023年11月09日 15:03:34
 */
public class ApplicationContextUtil {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextUtil.class);

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext ac) {
        applicationContext = ac;
    }

    private static ApplicationContext applicationContext;

    /**
     * 根据Clazz 类型在 IOC 容器中获取对象
     *
     * @param clazz class类型
     * @param <T>   获取的对象泛型
     * @return 需要返回的泛型组件
     */
    public static <T> List<T> getBeanByType(Class<T> clazz) {
        List<T> list = new ArrayList<>();

        // 获取接口的所有实例名
        String[] beanNames = applicationContext.getBeanNamesForType(clazz);
        logger.debug("getBeanByType beanNames : {}", CollectionUtils.isEmpty(Arrays.asList(beanNames))
                ? ""
                : Arrays.toString(beanNames));
        if (CollectionUtils.isEmpty(Arrays.asList(beanNames))) {
            return list;
        }

        // 获取 bean， 添加值返回集合
        T t;
        for (String beanName : beanNames) {
            t = (T) applicationContext.getBean(beanName);
            list.add(t);
        }
        return list;
    }

}
